package hoang.hut.app.utility.file;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;


public class FileUtility {
	/**
	 * convert InputStream to String
	 * 
	 * @param stream
	 * @return
	 * @throws IOException
	 */
	public static String readStringFromStream(InputStream stream)
			throws IOException {
		InputStreamReader isReader = new InputStreamReader(stream,
				Charset.forName("utf-8"));
		BufferedReader br = new BufferedReader(isReader);
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line).append("\n");
		}
		return sb.toString();
	}

	/**
	 * copy stream
	 * 
	 * @param is: doc file
	 * @param os: ghi file
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}
	/**
	 * convert inputstream to byte[]
	 * 
	 * @param is
	 * @return
	 */
	public static byte[] readstreamFully(InputStream is) {
		return readstreamFully(is, 1024);
	}
	public static byte[] readstreamFully(InputStream is, int blocksize) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[blocksize];
			while (true) {
				int len = is.read(buffer);
				if (len == -1) {
					break;
				}
				baos.write(buffer, 0, len);
			}
			return baos.toByteArray();
		} catch (Exception e) {
		}
		return new byte[0];
	}
}
